package online.keepon.wechatpush.utils;


import com.alibaba.fastjson.JSONObject;
import online.keepon.wechatpush.config.TianXingProperties;
import online.keepon.wechatpush.model.Dialogue;
import online.keepon.wechatpush.model.Weather;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author top
 */
@Component
public class TianApiUtil {


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private TianXingProperties properties;

    /**
     * 获取当天天气信息
     */
    public Weather getWeather() {
        Map<String, String> map = new HashMap<>(2);
        map.put("city", properties.getCity());
        map.put("key", properties.getApikey());
        String res = restTemplate.getForObject("https://apis.tianapi.com/tianqi/index?type=1&key={key}&city={city}", String.class, map);
        JSONObject json = JSONObject.parseObject(res);
        if (json != null && json.getInteger("code") == 200) {
            return JSONObject.parseObject(json.getJSONObject("result").toJSONString(), Weather.class);
        }
        return null;
    }

    /**
     * 彩虹屁
     */
    public String getRainbow() {
        String httpUrl = "https://apis.tianapi.com/caihongpi/index?key=" + properties.getApikey();
        String res = restTemplate.getForObject(httpUrl, String.class);
        JSONObject json = JSONObject.parseObject(res);
        if (json != null && json.getInteger("code") == 200) {
            return json.getJSONObject("result").getString("content");
        }
        return "";
    }

    /**
     * 经典台词
     */
    public Dialogue getDialogue() {
        String httpUrl = "https://apis.tianapi.com/dialogue/index?key=" + properties.getApikey();
        String res = restTemplate.getForObject(httpUrl, String.class);
        JSONObject json = JSONObject.parseObject(res);
        if (json != null && json.getInteger("code") == 200) {
            return JSONObject.parseObject(json.getJSONObject("result").toJSONString(), Dialogue.class);
        }
        return null;
    }


}
